package com.tamtamy.jtta.data.xml;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.tamtamy.jtta.data.UsersList;
import com.tamtamy.jtta.exception.NoResultException;
import com.tamtamy.jtta.exception.ParsingException;
import com.tamtamy.jtta.utility.XMLUtility;

public class XMLUsersList extends UsersList {

	private static final long serialVersionUID = -8080452612593858930L;

	private static final String KCLUSER = "it.reply.tt.rest.entity.KcLUser";
	
	public XMLUsersList(Document xmlDocument) throws NoResultException, ParsingException {
		super();
		NodeList usersNodeList = xmlDocument.getElementsByTagName(KCLUSER);
		if (usersNodeList == null || usersNodeList.getLength()==0){
			throw new NoResultException("No " + KCLUSER + " element found");
		}
		for (int i = 0; i < usersNodeList.getLength(); i++) {
			Node userNode = usersNodeList.item(i);
			try {
				Document userDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
				userDocument.appendChild(userDocument.importNode(userNode, true));
				this.add(new XMLUser(userDocument)); 
			} catch (ParserConfigurationException parserConfigurationException) {
				throw new ParsingException("Error parsing " + KCLUSER + " element : " + parserConfigurationException.getMessage());
			}
		}		
		setTotal(XMLUtility.getInt(xmlDocument, "total")); 
	}

}
